#include"../../util.h"
#include"ed_translate_model.h"
#include"../../../log/log_mgr.h"

EdTranslateModel::EdTranslateModel(string info)
{
	load(info);
}

EdTranslateModel::EdTranslateModel(DistCalc *dist_calc)
{
	this->dist_calc = dist_calc;
}

void EdTranslateModel::build(map<string, vector<pair<string, int>>> &pair_list, map<string, int> &translation_model)
{
	map<string, vector<pair<string, int>>>::iterator itr;
	for(itr = pair_list.begin(); itr != pair_list.end(); ++ itr)
	{
		string label = (*itr).first;
		vector<pair<string, int>> &v = (*itr).second;
		for(int i = 0; i < v.size(); ++ i){
			string cand = v[i].first;
			int freq = v[i].second;
			vector<int> align = dist_calc->dist_align(cand, label).second;
			int a_x = 0, a_y = 0;
			for(int j = 0; j < align.size(); ++ j){
				if(align[j] == -1)continue;
				if(cand[j] == ' ' && label[align[j] - 1] == ' '){
					string align_x = cand.substr(a_x, j - a_x);
					string align_y = label.substr(a_y, align[j] - a_y - 1);
					a_x = j + 1;
					a_y = align[j];
					string code = util::sort_s(align_x) + ">" + util::format(align_y);
					map<string, int>::iterator align_map_itr = translation_model.find(code);
					if(align_map_itr == translation_model.end())
						translation_model.insert(pair<string, int>(code, freq));
					else
						(*align_map_itr).second += freq;
				}
			}
		}
	}
}

void EdTranslateModel::load(string line)
{
	vector<string> pattern_list = util::tokenize_h(line, " | ");
	for(int i = 0; i < pattern_list.size(); ++ i)
	{
		string pattern = pattern_list[i];
		int del = pattern.find("\t");
		string trans = pattern.substr(0, del);
		string freq_c = pattern.substr(del + 1, pattern.length() - del - 1);
		int freq = atoi(freq_c.c_str());
		model.insert(pair<string, int>(trans, freq));
	}
}